package ltd.hyangyang.rpc.core.remoting.server;

import ltd.hyangyang.rpc.common.bean.RpcProperties;
import ltd.hyangyang.rpc.common.utils.SingletonFactory;
import ltd.hyangyang.rpc.core.registory.zook.CuratorUtils;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

public class CustomShutdownHook {

    static RpcProperties rpcProperties;

    static CuratorFramework client;

    static {
        rpcProperties = SingletonFactory.getSingletonBean(RpcProperties.class);
        try {
            client = CuratorUtils.init(rpcProperties.getAddr());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void clearAllNodes(){

        Runtime.getRuntime().addShutdownHook(new Thread(()->{

            //执行关闭
            ConcurrentHashMap<String, String> registryNodes = CuratorUtils.registryNodes;
            //获取到注册的所有的节点
            registryNodes.forEach((key,value)->{
                //删除
                if (!StringUtils.isEmpty(value)){
                    CuratorUtils.deleteNode(client,value);
                }

            });
        }));
    }
}
